package com.sky.service.impl;

import com.sky.constant.EmailConstant;
import com.sky.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public EmailServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送验证码到用户邮件
     */
    @Override
    public String sendSimpleMail(String emailReceiver) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(emailReceiver);
        message.setSubject(EmailConstant.EMAIL_THEME);

        // 生成4位随机验证码（修改部分）
        Random random = new Random();

        // 生成0-9999的随机整数
        int randomNum = random.nextInt(EmailConstant.EMAIL_RANDOM);

        // 格式化为6位字符串（不足补零）
        String code = String.format("%06d", randomNum);

        // 将验证码存入Redis
        redisTemplate.opsForValue().set(emailReceiver, code, 10, TimeUnit.MINUTES);

        String text = EmailConstant.EMAIL_CONTENT + code;
        message.setText(text);
        try {
            // 发送邮件
            javaMailSender.send(message);
            log.info("发送邮件成功，接收邮箱：{}", emailReceiver);
            return EmailConstant.SEND_SUCCESS;
        } catch (MailException e) {
            log.error("发送邮件失败，接收邮箱：{}", emailReceiver, e);
        }
        return EmailConstant.SEND_FAIL;
    }

    /**
     * 发送文本邮件给被回复者
     */
    @Override
    public void sendTextMail(String targetEmail, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(targetEmail);
        message.setSubject(subject);
        message.setText(body);
        try {
            // 发送邮件
            javaMailSender.send(message);
            log.info("发送邮件成功，接收邮箱：{}", targetEmail);
        } catch (MailException e) {
            log.error("发送邮件失败，接收邮箱：{}", targetEmail, e);
        }
    }

}
